package org.kl.wx.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.kl.bf.entity.basic.BasicFile;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.service.basic.BasicFileService;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.utils.ExcelWriter;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.kl.wx.entity.MaterialActicle;
import org.kl.wx.service.MaterialActicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

@Controller
@RequestMapping(value = "/wx/materialActicle")
public class MaterialActicleController extends BasicController {

	@Autowired
	private MaterialActicleService materialActicleService;
	@Autowired
	private BasicFileService basicFileService;

	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "/wx/materialActicleList";
	}

	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<MaterialActicle> materialActicle = materialActicleService.getMaterialActicle(searchParams, pageNumber, pageSize, sortType,
				orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(materialActicle.getContent(), (int) materialActicle.getTotalElements());
	}

	@RequestMapping(value = "update", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("materialActicle") MaterialActicle materialActicle,
			@RequestParam(value = "showCoverPicButton", defaultValue = "") String showCoverPicButton, BindingResult result) {
		if (result.hasErrors()) {
			return ajaxMsg(bindingMsg(result), false, null);
		}
		if (StringUtils.equals(showCoverPicButton, "on")) {
			materialActicle.setShowCoverPic(BasicConstants.YES_INT);
		} else {
			materialActicle.setShowCoverPic(BasicConstants.NO_INT);
		}
		try {
			materialActicleService.saveMaterialActicle(materialActicle);
			return ajaxMsg("保存成功", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("保存失败", false, null);
		}
	}

	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		try {
			materialActicleService.deleteMaterialActicle(id);
			return ajaxMsg("删除成功", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败", false, null);
		}
	}

	@RequestMapping(value = "getThumbMedia", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String getThumbMedia(@RequestParam(value = "id", defaultValue = "") String id, RedirectAttributes redirectAttributes) {
		BasicFile bf = basicFileService.getBasicFile(id);
		if (bf == null || StringUtils.isBlank(bf.getId())) {
			return ajaxMsg("获取失败", false, null);
		}
		return ajaxMsg("获取成功", true, bf);
	}

	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = materialActicleService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<MaterialActicle> materialActicle = materialActicleService.getMaterialActicle(searchParams, pageNumber, 0, sortType, orderType);
		try {
			// 输出Excel文件.
			response.setContentType("materialActiclelication/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment;filename=\""
							+ new String(("素材描述" + new DateTime().toString("yyyyMMddHHmmss") + ".xls").getBytes("gb2312"), "ISO8859-1")
							+ "\"");
			ExcelWriter.exportExcel("素材描述", MaterialActicle.class, materialActicle.getContent(), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@ModelAttribute
	public void getMaterialActicle(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("materialActicle", materialActicleService.getMaterialActicle(id));
		}
	}
}
